import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import Welcome from '../views/Welcome.vue'
import Users from '../views/Users.vue'
import Right from '../views/Rights.vue'
import Roles from '../views/Roles.vue'
import Cate from '../views/Cate.vue'
import Params from '../views/Params.vue'
import List from '../views/List.vue'
import Add from '../views/Add.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome },
        { path: '/users', component: Users },
        { path: '/rights', component: Right },
        { path: '/roles', component: Roles },
        { path: '/categories', component: Cate },
        { path: '/params', component: Params },
        { path: '/goods', component: List },
        { path: '/goods/add', component: Add }
      ]
    }
  ]
})

// 为路由对象添加beforeEach导航守卫
// to保湿将要访问的路径
// from代表从哪里来
// next是一个函数，表示放行next()
router.beforeEach((to, from, next) => {
  if (to.path !== '/login') {
    const token = sessionStorage.getItem('token')
    if (!token) return next('/login')
  }
  next()
})

// 暴露路由
export default router
